<template>
  <div class="announce-publish">
    <div class="page-header">
      <h2>发布公告</h2>
      <p>创建新的系统公告通知用户</p>
    </div>

    <div class="publish-content">
      <div class="form-section">
        <div class="form-group">
          <label for="announcement-title">公告标题</label>
          <input
              id="announcement-title"
              v-model="announcement.title"
              type="text"
              placeholder="请输入公告标题"
              class="form-input"
              :disabled="loading"
              maxlength="200"
          />
          <div class="input-counter">{{ announcement.title?.length || 0 }}/200</div>
        </div>

        <div class="form-group">
          <label for="announcement-content">公告内容</label>
          <div class="textarea-container">
            <textarea
                id="announcement-content"
                v-model="announcement.content"
                placeholder="请输入公告内容"
                rows="6"
                class="form-textarea"
                :disabled="loading"
                maxlength="2000"
            ></textarea>
            <div class="textarea-counter">{{ announcement.content?.length || 0 }}/2000</div>
          </div>
        </div>

        <!-- 新增：公告类型选择 -->
        <div class="form-group">
          <label for="announcement-type">公告类型</label>
          <div class="select-container">
            <select
                id="announcement-type"
                v-model="announcement.type"
                class="form-input"
                :disabled="loading"
            >
              <option value="运营通知">运营通知</option>
              <option value="课程上新">课程上新</option>
              <option value="系统维护">系统维护</option>
            </select>
            <i class="fa fa-chevron-down select-arrow"></i>
          </div>
        </div>

        <!-- 新增：预约发布时间 -->
        <div class="form-group">
          <label for="announcement-scheduled-time">预约发布时间（可选）</label>
          <input
              id="announcement-scheduled-time"
              v-model="announcement.scheduledPublishTime"
              type="datetime-local"
              class="form-input"
              :disabled="loading"
              :min="minDateTime"
          />
          <div class="help-text">如果不选择，将立即发布公告</div>
        </div>


        <div class="form-actions">
          <button class="reset-btn" @click="resetForm" :disabled="loading">
            <i class="fa fa-refresh"></i>
            重置
          </button>
          <button class="publish-btn" @click="publishAnnouncement" :disabled="loading">
            <i class="fa fa-bullhorn"></i>
            {{ loading ? '发布中...' : announcement.scheduledPublishTime ? '预约发布' : '立即发布' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'

export default {
  name: 'AnnouncePublish',
  setup() {
    const router = useRouter()
    const loading = ref(false)

    const announcement = ref({
      title: '',
      content: '',
      publisher: '管理员',
      type: '运营通知', // 默认类型
      scheduledPublishTime: '', // 预约发布时间
      status: 0 // 默认状态为草稿
    })

    // 计算最小日期时间（当前时间）
    const minDateTime = computed(() => {
      const now = new Date()
      // 转换为本地日期时间字符串格式
      return now.toISOString().slice(0, 16)
    })

    const publishAnnouncement = async () => {
      if (!announcement.value.title.trim() || !announcement.value.content.trim()) {
        alert('请填写公告标题和内容')
        return
      }

      if (!announcement.value.type) {
        alert('请选择公告类型')
        return
      }

      loading.value = true
      try {
        // 处理发布时间和状态逻辑
        const hasScheduledTime = announcement.value.scheduledPublishTime
        let scheduledPublishTime = null

        if (hasScheduledTime) {
          // 创建本地时间对象
          const localDate = new Date(announcement.value.scheduledPublishTime)

          // 手动构建东八区时间字符串 (GMT+8)
          const year = localDate.getFullYear()
          const month = String(localDate.getMonth() + 1).padStart(2, '0')
          const day = String(localDate.getDate()).padStart(2, '0')
          const hours = String(localDate.getHours()).padStart(2, '0')
          const minutes = String(localDate.getMinutes()).padStart(2, '0')
          const seconds = String(localDate.getSeconds()).padStart(2, '0')

          // 格式: yyyy-MM-ddTHH:mm:ss (后端期望的格式)
          scheduledPublishTime = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`
        } else {
          // 如果没有选择预约时间，使用当前东八区时间
          const now = new Date()
          const year = now.getFullYear()
          const month = String(now.getMonth() + 1).padStart(2, '0')
          const day = String(now.getDate()).padStart(2, '0')
          const hours = String(now.getHours()).padStart(2, '0')
          const minutes = String(now.getMinutes()).padStart(2, '0')
          const seconds = String(now.getSeconds()).padStart(2, '0')

          scheduledPublishTime = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`
        }

        const publishData = {
          title: announcement.value.title,
          content: announcement.value.content,
          type: announcement.value.type,
          scheduledPublishTime: scheduledPublishTime,
          // 如果选择了预约时间，状态为草稿(0)，否则为已发布(1)
          status: hasScheduledTime ? 0 : 1
        }

        console.log('发布数据:', publishData)

        const response = await fetch('http://localhost:8081/api/announcements/insert', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify(publishData)
        })

        const result = await response.json()

        if (result.code === 200) {
          if (announcement.value.scheduledPublishTime) {
            alert('公告预约发布成功！')
          } else {
            alert('公告发布成功！')
          }
          resetForm()
          // 跳转到公告列表页面
          setTimeout(() => {
            router.push('/admin/dashboard/announce-list')
          }, 1000)
        } else {
          alert(result.message || '发布失败')
        }
      } catch (error) {
        console.error('发布公告失败:', error)
        alert('网络错误，请稍后重试')
      } finally {
        loading.value = false
      }
    }

    const resetForm = () => {
      announcement.value = {
        title: '',
        content: '',
        publisher: '管理员',
        type: '运营通知',
        scheduledPublishTime: '',
        status: 0
      }
    }

    return {
      announcement,
      loading,
      minDateTime,
      publishAnnouncement,
      resetForm
    }
  }
}
</script>

<style scoped>
.announce-publish {
  padding: 0;
}

.page-header {
  margin-bottom: 2rem;
}

.page-header h2 {
  color: #f8fafc;
  font-size: 1.8rem;
  margin-bottom: 0.5rem;
}

.page-header p {
  color: #94a3b8;
  font-size: 1rem;
}

.publish-content {
  background: rgba(15, 23, 42, 0.6);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 16px;
  padding: 2rem;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.2);
}

.form-section {
  max-width: 600px;
  width: 100%; /* 添加这一行确保容器宽度一致 */
}

.form-input,
.form-textarea,
.select-container select {
  width: 100%;
  padding: 0.75rem 1rem;
  border: 2px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  font-size: 1rem;
  transition: all 0.3s ease;
  background-color: rgba(255, 255, 255, 0.05);
  color: #f8fafc;
  box-sizing: border-box;
  appearance: none; /* 隐藏浏览器默认箭头 */
  -webkit-appearance: none; /* Safari 和 Chrome */
  -moz-appearance: none; /* Firefox */
}
/* 添加下拉选项的样式 */
.select-container select option {
  background: rgba(15, 23, 42, 0.95); /* 深色背景 */
  color: #f8fafc; /* 浅色文字 */
  padding: 0.75rem 1rem; /* 内边距 */
  border: none; /* 无边框 */
  font-size: 1rem; /* 字体大小 */
}
/* 鼠标悬停选项样式 */
.select-container select option:hover {
  background: rgba(102, 126, 234, 0.3); /* 悬停时的背景色 */
}

/* 选中选项样式 */
.select-container select option:checked {
  background: rgba(102, 126, 234, 0.5); /* 选中时的背景色 */
  color: white; /* 选中时的文字颜色 */
}

.form-group {
  display: flex;
  flex-direction: column;
  margin-bottom: 1.5rem;
}

.form-group label {
  margin-bottom: 0.5rem;
  color: #e2e8f0;
  font-weight: 600;
}

.form-input, .form-textarea {
  padding: 0.75rem 1rem;
  border: 2px solid rgba(255, 255, 255, 0.1);
  border-radius: 8px;
  font-size: 1rem;
  transition: all 0.3s ease;
  background-color: rgba(255, 255, 255, 0.05);
  color: #f8fafc;
}

.form-input::placeholder, .form-textarea::placeholder {
  color: #64748b;
}

.form-input:focus, .form-textarea:focus {
  outline: none;
  border-color: #667eea;
  background-color: rgba(255, 255, 255, 0.08);
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.15);
}

.form-textarea {
  resize: vertical;
  min-height: 120px;
  font-family: inherit;
}

/* 确保选择框容器宽度一致 */
.select-container {
  position: relative;
  width: 100%; /* 添加这一行 */
}

.select-arrow {
  position: absolute;
  right: 1rem;
  top: 50%;
  transform: translateY(-50%);
  color: #64748b;
  pointer-events: none;
}

.form-input[type="datetime-local"] {
  width: 100%;
  font-family: inherit;
  box-sizing: border-box;
}

.help-text {
  font-size: 0.8rem;
  color: #94a3b8;
  margin-top: 0.25rem;
}

.input-counter, .textarea-counter {
  text-align: right;
  font-size: 0.75rem;
  color: #94a3b8;
  margin-top: 0.25rem;
}

.textarea-container {
  position: relative;
  width: 100%;
}

.form-actions {
  display: flex;
  gap: 1rem;
  margin-top: 2rem;
  justify-content: flex-end;
}

.publish-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  padding: 0.75rem 1.5rem;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 0.5rem;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
}

.publish-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(102, 126, 234, 0.4);
}

.publish-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.reset-btn {
  background: rgba(255, 255, 255, 0.08);
  color: #cbd5e0;
  border: 1px solid rgba(255, 255, 255, 0.1);
  padding: 0.75rem 1.5rem;
  border-radius: 8px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.reset-btn:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.12);
  color: white;
}

.reset-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

@media (max-width: 768px) {
  .publish-content {
    padding: 1.5rem;
  }

  .form-actions {
    flex-direction: column;
  }
}
</style>